package com.nettyAdvanced.p1;

import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;

import java.net.InetSocketAddress;

/**
 * @author： pang-yun
 * @date： 2021-09-14 15:34
 * 功能目的 ：用于  观察黏包现象的 客户端
 */

public class HelloWorldClient {
    public static void main(String[] args) throws InterruptedException {
        NioEventLoopGroup clientWork = new NioEventLoopGroup();

        try {
            ChannelFuture channelFuture = new Bootstrap()
                    .group(clientWork)
                    .channel(NioSocketChannel.class)
                    .handler(new ChannelInitializer<NioSocketChannel>() {
                        @Override
                        protected void initChannel(NioSocketChannel ch) throws Exception {
                            ch.pipeline().addLast(new ChannelInboundHandlerAdapter() {

                                //channel  建立连接之后 会触发 active事件
                                @Override
                                public void channelActive(ChannelHandlerContext ctx) throws Exception {
                                    for (int i=0;i<10;i++){
                                        ByteBuf buffer = ctx.alloc().buffer(10);
                                        buffer.writeBytes(new byte[]{1,2,3,4,5,6,7,8,9,0});
                                        ctx.writeAndFlush(buffer);
                                    }

                                }
                            });
                        }
                    }).connect(new InetSocketAddress(9999));

            Channel channel = channelFuture.sync().channel();
        } catch (InterruptedException e) {
            System.out.println("error");
        } finally {
            clientWork.shutdownGracefully();
        }

    }

}
//------10次结果 没有分批次发送  而是出现了黏包
/*         +-------------------------------------------------+
         |  0  1  2  3  4  5  6  7  8  9  a  b  c  d  e  f |
+--------+-------------------------------------------------+----------------+
|00000000| 01 02 03 04 05 06 07 08 09 00 01 02 03 04 05 06 |................|
|00000010| 07 08 09 00 01 02 03 04 05 06 07 08 09 00 01 02 |................|
|00000020| 03 04 05 06 07 08 09 00 01 02 03 04 05 06 07 08 |................|
|00000030| 09 00 01 02 03 04 05 06 07 08 09 00 01 02 03 04 |................|
|00000040| 05 06 07 08 09 00 01 02 03 04 05 06 07 08 09 00 |................|
|00000050| 01 02 03 04 05 06 07 08 09 00 01 02 03 04 05 06 |................|
|00000060| 07 08 09 00                                     |....            |
+--------+-------------------------------------------------+----------------+*/